#include <sqlite3.h>
#include <stdio.h>

/*
	有时，我们需要确定最后插入行的 id。为此，我们有了函数。
	sqlite3_last_insert_rowid()	

	gcc -o last_row_id last_row_id.c -lsqlite3
	./last_row_id

	运行结果：
	
	Table Friends created successfully
	The last Id of the inserted row is 6

	可见Id从一开始自增
*/

int main(void) {
    
    sqlite3 *db;
    char *err_msg = 0;
    
    int rc = sqlite3_open("test.db", &db);
    
    if (rc != SQLITE_OK) {
        
        fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        
        return 1;
    }

    /*在内存中创建一个表。其列会自动递增。FriendsId*/
    
    //char *sql = "CREATE TABLE Friends(Id INTEGER PRIMARY KEY, Name TEXT);"
    char *sql = "DROP TABLE IF EXISTS Friends;"
    "CREATE TABLE Friends(Id INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT);"
    "INSERT INTO Friends(Name) VALUES ('Tom');"
    "INSERT INTO Friends(Name) VALUES ('Rebecca');"
    "INSERT INTO Friends(Name) VALUES ('Jim');"
    "INSERT INTO Friends(Name) VALUES ('Roger');"
    "INSERT INTO Friends(Name) VALUES ('Robert');"
    "INSERT INTO Friends(Name) VALUES ('Lizhiyi');";
    /*在 SQLite 中，列是自动递增的。还有一个关键字。
    当应用于略有不同的 Id 创建算法时，将使用。
    INTEGER PRIMARY KEYAUTOINCREMENTINTEGER PRIMARY KEY AUTOINCREMENT*/    
    
    rc = sqlite3_exec(db, sql, 0, 0, &err_msg);
    
    if (rc != SQLITE_OK ) {
        
        fprintf(stderr, "Failed to create table\n");
        fprintf(stderr, "SQL error: %s\n", err_msg);
        sqlite3_free(err_msg);
        
    } else {
        
        fprintf(stdout, "Table Friends created successfully\n");
    }
    
    int last_id = sqlite3_last_insert_rowid(db);
    printf("The last Id of the inserted row is %d\n", last_id);

    sqlite3_close(db);
    
    return 0;
}

